package cn.edu.nju.notification;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONObject;

import cn.edu.nju.R;
import cn.edu.nju.storage.StoreDataProvider;

import android.app.Activity;
import android.util.Log;

public class NotificationProvider {
	private static NotificationProvider provider;
	private List<AtNotification> atNotifications;
	private List<SystemNotification> systemNotifications;
	Activity activity;

	private long userId;

	public static NotificationProvider getInstance(Activity activity) {
		if (provider == null) {
			provider = new NotificationProvider(activity, StoreDataProvider
					.getInstance(activity).getUserId());
		}
		return provider;
	}

	private NotificationProvider(Activity activity, long userId) {
		// init system notification and at notification
		this.activity = activity;
		this.userId = userId;
	}

	public int getNotificationNumber() {
		// we get the total notification number before download any notification
		int number = Integer.parseInt(connectServer("totalNumber"));
		return number;
	}

	public List<SystemNotification> getSystemNotifications() {
		return systemNotifications;
	}

	public void clearSystemNotification() {
		// TODO update the server
		String result = connectServer("clearSys");
		if (result.equals("OK")) {
			systemNotifications.clear();
		} else {

		}
	}

	public List<AtNotification> getAtNotifications() {
		return atNotifications;
	}

	public void clearAtNotification() {
		// TODO update the server
		String result = connectServer("clearAt");
		if (result.equals("OK")) {
			atNotifications.clear();
		} else {
			// TODO
		}
	}

	// download data from server
	public void refresh() {
		systemNotifications = new ArrayList<SystemNotification>();
		atNotifications = new ArrayList<AtNotification>();

		String string = connectServer("getNotification");
		try {
			JSONArray array = new JSONArray(string);

			for (int i = 0; i < array.length(); i++) {
				JSONObject object = array.getJSONObject(i);
				int type = object.getInt("isFromSystem");
				if (type == 0) {
					atNotifications.add(new AtNotification(object
							.getString("summary"), activity, object
							.getLong("news_id")));
				} else {
					systemNotifications
							.add(new SystemNotification(object
									.getString("summary"), object
									.getString("content")));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String connectServer(String mode) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(
					activity.getString(R.string.server_url)
							+ "notification.php");

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			entity.addPart("id", new StringBody("" + StoreDataProvider.getInstance(activity).getUserId()));
			entity.addPart("option", new StringBody(mode));

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));

			String context = reader.readLine();
			reader.close();
			return context;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
}
